<template>
  <div class="main_box" style="padding:10px">
    <el-card class="add-wrapper">
      <el-tabs v-model="module">
        <el-tab-pane :label="title" name="first">
          <el-form :model="dataForm" ref="dataForm" label-width="130px" :rules="roleRules">
            <el-form-item label="商户全称:" prop="businessName">
              <el-input v-model="dataForm.businessName" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户简称:" prop="businessShortName">
              <el-input v-model="dataForm.businessShortName" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户昵称(最简名称):" prop="businessMiniName">
              <el-input v-model="dataForm.businessMiniName" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户介绍:" prop="introduce">
              <el-input type="textarea" v-model="dataForm.introduce" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户类型:" prop="businessType">
              <el-select v-model="dataForm.businessType" clearable>
                <el-option v-for="item in businessTypeList" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="详细类型" prop="detailType">
              <el-select v-model="dataForm.detailType" clearable>
                <el-option v-for="item in detailTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <!-- <el-radio-group v-model="dataForm.detailType">
								<el-radio :label="2">是</el-radio>
								<el-radio :label="1">否</el-radio>
							</el-radio-group> -->
            </el-form-item>
            <el-form-item label="平台商户:" prop="parentBusinessId" v-show="dataForm.businessType != 3">
              <el-select v-model="dataForm.parentBusinessId" clearable filterable @change="()=>{
                if(dataForm.parentBusinessId){
                  getCheckoutInfo(dataForm.parentBusinessId)
                }else{
                  verifyDiscount = 0
                }
              }">
                <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="commission" label="总部管理费占比:" v-show="dataForm.businessType == 3">
              <el-input v-maxnum="{
                obj: dataForm,
                key: 'commission',
                max: 100,
                zero: true
              }" v-model.number="dataForm.commission">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
            <el-form-item label="经营方式" prop="manageType">
              <el-select v-model="dataForm.manageType" clerable>
                <el-option v-for="item in manageList" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务分类(多选):" prop="serverClassifyIds">
              <!-- <el-select
                v-model="dataForm.serverClassifyIds"
                multiple
                filterable
                clearable
              >
                <el-option
                  v-for="item in serverLevel2List"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                >
                </el-option>
              </el-select> -->
              <el-cascader filterable v-model="dataForm.serverClassifyIds" placeholder="请选择服务分类"
                :options="serverLevel2List" :props="{ multiple: true, value: 'id', label: 'name', emitPath: false }"
                clearable :show-all-levels="false"></el-cascader>
            </el-form-item>
            <!-- <el-form-item label="关联医院" prop="hospitalId">
							<el-select v-model="dataForm.hospitalId" clearable filterable>
								<el-option v-for="item in hospitalList" :label="item.name" :value="item.id" :key="item.id"></el-option>
							</el-select>
						</el-form-item> -->
            <el-form-item prop="discount" label="商户折扣比例:">
              <el-input type="number" v-model.number="dataForm.discount" @input="handleInput('discount')">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
            <el-form-item label="联系人:" prop="linkName">
              <el-input v-model="dataForm.linkName" clearable></el-input>
            </el-form-item>
            <el-form-item label="联系人性别:" prop="sex">
              <el-radio-group v-model="dataForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系电话:" prop="linkPhone">
              <el-input type="number" v-model="dataForm.linkPhone" clearable></el-input>
            </el-form-item>
            <el-form-item label="备用电话:" prop="linkPhoneTwo">
              <el-input type="number" v-model="dataForm.linkPhoneTwo" clearable></el-input>
            </el-form-item>
            <el-form-item label="所在地区:" prop="streetIds">
              <Address :addressList="dataForm.streetIds" @getAddress="handleItemChange"></Address>
              <!-- <Region :streetValues="dataForm.streetIds" @regionChange="handleItemChange"></Region> -->
            </el-form-item>
            <el-form-item label="详细地址:" prop="address">
              <el-input v-model="dataForm.address" clearable></el-input>
            </el-form-item>
            <el-form-item label="经纬度:" prop="lnglat">
              <el-input v-model="dataForm.lnglat" placeholder="例如：112.926478,28.294984">
                <!--<el-button slot="append" @click="getLngLat" icon="el-icon-search">查询</el-button>-->
              </el-input>
              <el-button type="text" @click="getLngLat(1)">百度地图</el-button>
              <el-button type="text" @click="getLngLat(2)">腾讯地图</el-button>
            </el-form-item>
            <!-- <el-form-item label="营业时间:" prop="BusinessHours">
							<el-time-picker style="background-color: #F7F7F7;" size="mini" is-range
								v-model="dataForm.businessHours" range-separator="至" start-placeholder="开始时间"
								end-placeholder="结束时间" placeholder="选择时间范围" format="HH:mm" value-format="HH:mm">
							</el-time-picker>
						</el-form-item> -->
<!--            <el-form-item label="商户营业状态:" prop="businessState" v-if="dataForm.businessId && dataForm.businessState > 0">
              <el-select v-model="dataForm.businessState" clearable>
                <el-option v-for="item in businessStateList" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>-->

            <el-form-item label="推广员:" prop="promoterId" v-if="userRole == 1 && detailRole == 1">
              <el-select v-model="dataForm.promoterId" placeholder="请选择推广员" clearable>
                <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="维护员:" prop="keeperId" v-if="userRole == 1 && detailRole == 1">
              <el-select v-model="dataForm.keeperId" placeholder="请选择维护员" clearable>
                <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备 注:" prop="remark">
              <el-input type="textarea" v-model="dataForm.remark"></el-input>
            </el-form-item>
            <el-form-item prop="businessLogo" label="商户Logo:">
              <upload-img class="upload-img" @uploadFileList="getImgUrl" :param="{ type: 1 }" folder="businessLogo">
                <img v-if="dataForm.businessLogo" width="100%" :src="dataForm.businessLogo" alt="" />
                <div class="tip" v-if="!dataForm.businessLogo">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将图片拖到此处，或<em>点击上传</em>
                  </div>
                </div>
              </upload-img>
            </el-form-item>
            <el-form-item prop="businessLicense" label="营业执照:">
              <upload-img class="upload-img" @uploadFileList="getImgUrl" :param="{ type: 5 }" folder="businessLicense">
                <img v-if="dataForm.businessLicense" width="100%" :src="dataForm.businessLicense" alt="" />
                <div class="tip">
                  <i class="el-icon-upload" v-if="!dataForm.businessLicense"></i>
                  <div v-if="!dataForm.businessLicense" class="el-upload__text">
                    将图片拖到此处，或<em>点击上传</em>
                  </div>
                </div>
              </upload-img>
            </el-form-item>
          </el-form>
          <div class="btn-wrapper" v-if="dataForm.businessId">
            <el-button plain type="primary" @click="handleUpdateBusiness">保 存</el-button>
            <el-button type="primary" plain @click="handleNextOperate('second')">
              下一步
            </el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="营业设置" name="second">
          <el-form :model="dataForm" ref="dataForm2" label-width="180px" class="el-form__two" :rules="roleRules2">
            <el-row>
              <el-form-item label="自动营业或打烊">
                <el-switch v-model="dataForm.autoOpen" :active-value="1" :inactive-value="0">
                </el-switch>
              </el-form-item>
              <el-form-item label="支付后自动打印" v-if="dataForm.businessId">
                <el-switch v-model="dataForm.autoPrint" :active-value="1" :inactive-value="0"
                  @change="handlePrintAccept('autoPrint')">
                </el-switch>
              </el-form-item>
              <el-form-item label="接单后自动打印" v-if="dataForm.businessId">
                <el-switch v-model="dataForm.autoAcceptPrint" :active-value="1" :inactive-value="0"
                  @change="handlePrintAccept('autoAcceptPrint')">
                </el-switch>
              </el-form-item>
              <el-form-item label="自动接单" v-if="dataForm.businessId">
                <el-switch v-model="dataForm.autoAccept" :active-value="1" :inactive-value="0"
                  @change="handlePrintAccept('autoAccept')">
                </el-switch>
              </el-form-item>
              <el-form-item label="自动完成订单时间" prop="autoCompleteHours" v-if="dataForm.businessId">
                <el-input v-model="dataForm.autoCompleteHours" @input="handleInput('autoCompleteHours')">
                  <span slot="suffix">小时</span>
                </el-input>
              </el-form-item>

              <!-- <el-form-item label="起步价">
								<el-input v-model="dataForm.startPrice" type="number" @input="handleInput('startPrice')">
									<span slot="suffix">元</span>
								</el-input>
							</el-form-item> -->
              <el-form-item label="公共服务员配送比例">
                <el-input v-model="dataForm.percentage" @input="handleInput('percentage')">
                  <span slot="suffix">%</span>
                </el-input>
              </el-form-item>
              <el-form-item label="打包费折扣比例">
                <el-input type="number" v-model.number="dataForm.packageDiscount" @input="handleInput('packageDiscount')">
                  <span slot="suffix">%</span>
                </el-input>
              </el-form-item>
              <tip-form-item label="超单数量" tip="公共服务员一次最多接单数量" prop="exceedOrderNum">
                <el-input v-model="dataForm.exceedOrderNum"
                  v-maxnum="{ obj: dataForm, key: 'exceedOrderNum', int: true }"></el-input>
              </tip-form-item>
              <tip-form-item label="单次超时未结单时间" prop="taskSingleTimeout" tip="设置时间内服务员未接单就自动切换服务员">
                <el-input v-maxnum="{
                  obj: dataForm,
                  key: 'taskSingleTimeout',
                  int: true
                }" v-model="dataForm.taskSingleTimeout">
                  <template slot="append">分钟</template>
                </el-input>
              </tip-form-item>
              <tip-form-item label="总次超时未结单时间" prop="taskTotalTimeout" tip="设置时间内服务员已接单未完成就打电话提醒商户">
                <el-input v-maxnum="{
                  obj: dataForm,
                  key: 'taskSingleTimeout',
                  int: true
                }" v-model="dataForm.taskTotalTimeout">
                  <template slot="append">
                    分钟
                  </template>
                </el-input>
              </tip-form-item>
            </el-row>
            <el-row>
              <el-form-item prop="printModel" label="打印模板类型">
                <el-radio-group v-model="dataForm.printModel">
                  <el-radio :label="1">有价格</el-radio>
                  <el-radio :label="2">无价格</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="voiceFlag" label="语音单类型">
                <el-radio-group v-model="dataForm.voiceFlag">
                  <el-radio :label="0">无</el-radio>
                  <el-radio :label="1">普通商户</el-radio>
                  <!-- <el-radio :label="2">平台商户</el-radio> -->
                </el-radio-group>
              </el-form-item>
              <el-form-item label="语音接单等级:" prop="voiceLevel" v-if="dataForm.voiceFlag">
                <el-input v-model="dataForm.voiceLevel" clearable>
                  <span slot="suffix">(等级范围：1-10)</span>
                </el-input>
              </el-form-item>
              <!--							<el-form-item prop="openFlag" label="开通周边服务">
								<el-radio-group v-model="dataForm.openFlag">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否</el-radio>
								</el-radio-group>
							</el-form-item>-->
              <el-form-item prop="allowMonthSettle" label="支持线下月结">
                <el-radio-group v-model="dataForm.allowMonthSettle">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="allowOpenPhone" label="开通电话提醒">
                <el-radio-group v-model="dataForm.allowOpenPhone">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="服务员下班方式">
                <el-radio-group v-model="dataForm.workOffWay">
                  <el-radio :label="1">可自动打卡下班</el-radio>
                  <el-radio :label="2">仅手动打卡下班</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="服务员接单方式">
                <el-radio-group v-model="dataForm.takeOrdersWay">
                  <el-radio :label="2">可自动接单</el-radio>
                  <el-radio :label="1">仅手动接单</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-row>
          </el-form>
          <div style="width:500px">
            <div style="justify-content: space-between;align-items: center;display: flex;">
              <h2>
                营业时间
              </h2>
              <el-button plain type="success" icon="el-icon-plus" circle @click="addTime()">
              </el-button>
            </div>
            <el-table :data="dataForm.hours" max-height="800" style="margin-top: 5px;">
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button plain type="danger" icon="el-icon-minus" circle @click="subTime(scope.$index)">
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="开始时间" align="center">
                <template slot-scope="scope">
                  <el-time-picker is-range v-model="scope.row.list" range-separator="至" value-format="HH:mm"
                    format="HH:mm" :picker-options="{ format: 'HH:mm' }" start-placeholder="开始时间" end-placeholder="结束时间"
                    placeholder="选择时间范围">
                  </el-time-picker>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="btn-wrapper" v-if="dataForm.businessId">
            <el-button plain type="primary" @click="handlePortionInfo">保 存</el-button>
            <el-button type="primary" plain @click="handleNextOperate('first')">
              上一步
            </el-button>
            <el-button type="primary" plain @click="handleNextOperate('third')">
              下一步
            </el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="经营范围" name="third">
          <!-- dataForm.detailType == 2 ||
                dataForm.detailType == 1 -->
          <div style="margin-top:20px;width: max-content;" v-show="dataForm.detailType != ''"
            v-for="item in dataForm.businessVillages" :key="item.type">
            <div class="bussiness-villgae-header">
              <div>
                范围类型 ->
                <el-tag size="mini" effect="dark">
                  {{ formatVillageType(item.type) }}
                </el-tag>
              </div>
              <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtnRegion(item.type)">
              </el-button>
            </div>
            <el-table :max-height="800" :data="item.villages" style="width:max-content;">
              <el-table-column label="操作" width="110" align="center">
                <template slot-scope="scope">
                  <el-button icon="el-icon-minus" type="danger" plain size="medium" circle
                    @click="subBtnRegion(scope.row.type, scope.$index)">
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="省市区" width="320" align="center" v-if="item.type == 2 || item.type == 4">
                <template slot-scope="scope">
                  <Address style="width:300px" :isCheckStrictly="true" :level="3" :addressList="scope.row.streetIds"
                    @getAddress="handleItemChange" :index="scope.$index" :mark="{ type: scope.row.type }"></Address>
                </template>
              </el-table-column>
              <el-table-column label="小区" width="280" align="center" v-if="item.type == 2">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.villageId" style="width: 240px;" @focus="
                    handleVillageFocus(
                      scope.row.type,
                      scope.row.streetIds,
                      scope.$index
                    )
                    " @change="handleVillageChange(scope.row, scope.$index)" clearable filterable>
                    <el-option v-for="item in scope.row.villageList" :value="item.id" :label="item.name" :key="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="呼叫器ID(多个以英文逗号,隔开)" width="320" align="center" v-if="item.type == 1">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.beeperIds" placeholder="请输入呼叫器ID" clearable></el-input>
                </template>
              </el-table-column>
              <template v-if="item.type == 3">
                <el-table-column label="公里数" width="320" align="center">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.kilometers" placeholder="请输入公里数" clearable></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="经度" width="300" align="center">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.longitude" placeholder="请输入经度" clearable>
                      <el-button slot="append" @click="getLngLat(1)">百度地图</el-button>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="纬度" width="300" align="center">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.latitude" placeholder="请输入纬度" clearable>
                      <el-button slot="append" @click="getLngLat(2)">腾讯地图</el-button>
                    </el-input>
                  </template>
                </el-table-column>
              </template>
              <el-table-column label="起步价" width="260" align="center">
                <template slot-scope="scope">
                  <el-input type="text" v-maxnum="{ obj: scope.row, key: 'startPrice' }" v-model="scope.row.startPrice" />
                </template>
              </el-table-column>
              <el-table-column label="开通周边服务" width="120" align="center" v-if="item.type == 3 || item.type == 4">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.openFlag">
                    <el-option label="否" :value="0"></el-option>
                    <el-option label="是" :value="1"></el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="btn-wrapper" v-if="dataForm.businessId" size="small">
            <el-button plain type="primary" v-if="dataForm.businessId" @click="handleUpdateScope">
              保 存
            </el-button>
            <el-button type="primary" plain @click="handleNextOperate('second')">
              上一步
            </el-button>
            <el-button type="primary" plain @click="handleNextOperate('fourth')">
              下一步
            </el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="其它信息" name="fourth">
          <div class="fourth-title">
            <span>服务轮播图片</span>
            <el-button type="success" plain circle icon="el-icon-plus" @click="
              dataForm.banners.push($options.data().dataForm.banners[0])
              "></el-button>
          </div>
          <div>
            <el-table :data="dataForm.banners" style="max-width: 100%;">
              <el-table-column label="删除" width="100px" align="center">
                <template slot-scope="scope">
                  <el-button type="danger" plain circle icon="el-icon-minus"
                    @click="dataForm.banners.splice(scope.$index, 1)"></el-button>
                </template>
              </el-table-column>
              <el-table-column label="服务分类" width="250px" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.serverClassifyId" label="请选择服务分类" clearable filterable>
                    <el-option v-for="item in getServerClassifyList(
                      scope.row.serverClassifyId
                    )" :value="item.id" :label="item.name" :key="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="轮播图片">
                <template slot-scope="scope">
                  <UploadOssFile :limit="maxImgNum" :list="scope.row.list" @getImgVideo="getImgVideo" :showFlag="true"
                    :showSetMain="false" :mark="{ id: scope.row.id }" folder="classifyBannerImg"></UploadOssFile>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140" align="center" position="right">
                <template slot-scope="scope">
                  <el-button v-show="scope.row.serverClassifyId" type="primary" plain size="mini"
                    @click="handlesCImgsDialog(scope.row, scope.$index)">选择分类图片</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="btn-wrapper" v-if="dataForm.businessId" size="small">
            <el-button plain type="primary" v-if="dataForm.businessId" @click="handleBanners">
              保 存
            </el-button>
            <el-button type="primary" plain @click="handleNextOperate('third')">
              上一步
            </el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="btn-wrapper" v-if="!dataForm.businessId">
        <el-button type="primary" plain @click="sureClick">
          提 交
        </el-button>
        <el-button plain @click="returnList">取 消</el-button>
      </div>
    </el-card>
    <!-- <common-server-select ref="commonServerSelect" @getServerList="getServerList"></common-server-select> -->
    <!-- <ImageSelect :show="imageSelect.show" folder="classifyBannerImg" :limit="imageSelect.limit" @cancel="imageSelect.show = false"
      @getUrlList="getUrlList"></ImageSelect> -->
    <ServerClassifyImgs :serverClassifyId="sCImgs.serverClassifyId" :show.sync="sCImgs.show" @getUrlList="getUrlList">
    </ServerClassifyImgs>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import Address from "@/components/Address";
import VillageApi from "@/api/address/village";
import BusinessApi from "@/api/business/business";
import AccountInfoApi from "@/api/account/accountInfo";
import ServerClassifyApi from "@/api/server/serverClassify";
import { getStorage } from "@/utils/auth";
import { USER_INFO } from "@/constants/storeName";
import LoginApi from "@/api/system/login";
import UploadImg from "@/components/UploadImg";
import BusinessServerApi from "@/api/goods/businessServer";
import BusinessVillageApi from "@/api/business/businessVillage";
import CommonServerSelect from "../../components/CommonServerSelect";
import UploadOssFile from "../../components/UploadOssFile.vue";
import ImageSelect from "../../components/ImageSelect.vue";
import ServerClassifyImgs from "../../components/ServerClassifyImgs.vue";
// import HospitalApi from "../../api/institution/hospital";
import { nanoid } from "nanoid";
import SpecApi from '@/api/goods/spec';

export default {
  data() {
    return {
      verifyDiscount: 0,
      title: "基本信息",
      module: "first",
      userRole: "",
      detailRole: "",
      businessVillages: [],
      detailTypeList: [
        {
          label: "普通",
          value: 1 //
        },
        {
          label: "社区商家",
          value: 2
        },
        {
          label: "急救商家",
          value: 3
        },
        {
          label: "社区医院商家",
          value: 4
        },
        {
          label: "物业商家",
          value: 5
        }
      ],
      dataForm: {
        businessId: "",
        parentBusinessId: "",
        commission: "",
        businessState: "",
        businessType: "",
        businessName: "",
        businessShortName: "",
        businessMiniName: "",
        // hospitalId:"",
        introduce: "",
        manageType: 1,
        printModel: 1,
        shopFlag: 0,
        voiceFlag: 0,
        voiceLevel: 1,
        openFlag: 0,
        allowMonthSettle: 0,
        allowOpenPhone: 0,
        takeOrdersWay: 1,
        workOffWay: 1,
        exceedOrderNum: 3,
        taskSingleTimeout: "",
        taskTotalTimeout: "",
        businessLogo: "",
        businessLicense: "",
        discount: "",
        packageDiscount: 99.72,
        linkName: "",
        sex: 1,
        linkPhone: "",
        linkPhoneTwo: "",
        serverClassifyIds: "",
        streetIds: [],
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
        streetId: "",
        streetName: "",
        address: "",
        lnglat: "",
        longitude: "",
        latitude: "",
        businessHours: ["08:00", "20:00"],
        promoterId: "",
        keeperId: "",
        remark: "",
        // servers: [

        // 	{
        // 		//sort:"",//商品序号
        // 		serverClassifyId: "",
        // 		thirdClassifyId: "",
        // 		threeLevelClassList: [], //三级服务分类列表，不需要提交
        // 		name: "",
        // 		thirdClassifyName: "",
        // 		images: "",
        // 		introduce: "",
        // 		describes: "",
        // 		visitFlag: 1,//是否上门，1代表是
        // 		shopFlag: 0,//是否到店，1代表是，0代表不是
        // 		remoteFlag: 0,//是否远程，1代表是，0代表不是
        // 		fastFlag: 0,//紧急通知
        // 		deliveryFlag: 1,//是否需配送费
        // 		price: "",
        // 		salePrice: "",
        // 		deliveryFee: "",
        // 		packageFee: "", //包装费
        // 		discount: "",
        // 	}
        // ],

        autoOpen: 0,
        autoPrint: 0,
        autoAccept: 0,
        autoAcceptPrint: 0,
        autoCompleteHours: "",
        // startPrice: "",
        percentage: 5,
        hours: [
          {
            list: ["", ""]
          }
        ],
        businessVillages: [
          {
            type: 1,
            villages: [{ type: 1, startPrice: "", beeperIds: "", levels: 6 }] //呼叫器ID集合
          },
          {
            type: 2,
            villages: [
              {
                type: 2,
                startPrice: "",
                provinceId: "",
                provinceName: "",
                cityId: "",
                cityName: "",
                areaId: "",
                areaName: "",
                streetId: "",
                streetName: "",
                villageId: "",
                villageName: "",
                levels: 5,
                streetIds: [],
                villageList: []
              }
            ] //小区列表
          },
          {
            type: 3,
            villages: [
              {
                type: 3,
                startPrice: "",
                kilometers: "",
                levels: 7,
                longitude: "",
                latitude: "",
                openFlag: 0
              }
            ] //公里数
          },
          {
            type: 4,
            villages: [
              {
                type: 4,
                startPrice: "",
                provinceId: "",
                provinceName: "",
                cityId: "",
                cityName: "",
                areaId: "",
                areaName: "",
                streetIds: [],
                levels: 3,
                openFlag: 0
              }
            ] //省市区列表
          }
        ],
        banners: [
          {
            id: nanoid(),
            serverClassifyId: "",
            list: []
          }
        ],
        detailType: 1
      },
      maxImgNum: 10,
      bank: {
        show: false,
        cardType: ""
      },
      bankList: [{ code: 1, name: "银行1" }, { code: 2, name: "银行2" }],
      publicBranchBankList: [
        { code: 3, name: "公有支行1" },
        { code: 4, name: "公有支行2" }
      ],
      privateBranchBankList: [
        { code: 3, name: "公有支行1" },
        { code: 4, name: "公有支行2" }
      ],
      serverLevel2List: [], //服务分类二级列表
      // treeTwoServerList: [],//服务分类一二级列表
      // selectedServerList: [],//从serverLevel2List里面选择了服务分类之后形成新的服务分类列表
      businessList: [],
      sCImgs: {
        show: false,
        index: "",
        serverClassifyId: ""
      },
      businessStateList: [
        /*{ value: 0, label: "未开通" },*/
        { value: 1, label: "营业" },
        { value: 2, label: "打烊" }
      ],
      manageList: [
        { value: 1, label: "自运营" },
        { value: 2, label: "托管平台运营" },
        { value: 3, label: "独立运营" }
      ],
      scopeTypeList: [
        { value: 1, label: "专属" },
        { value: 2, label: "小区" },
        { value: 3, label: "公里数" },
        { value: 4, label: "省市区" }
      ],
      businessTypeList: [
        { value: 1, label: "大众" },
        { value: 2, label: "专属" },
        // { value: 3, label: "平台" },
        { value: 4, label: "经销" }
      ],
      roleList: [],
      loadingIns: false,
      roleRules: {
        streetIds: [
          { required: true, message: "请选择所在区", trigger: "change" }
        ],
        address: [
          { required: true, message: "请输入联系地址", trigger: "blur" }
        ],
        businessName: [
          { required: true, message: "请输入商户全称", trigger: "blur" }
        ],
        businessShortName: [
          { required: true, message: "请输入商户简称", trigger: "blur" },
          { max: 15, message: "商户简称不超过15个字", trigger: "blur" }
        ],
        businessMiniName: [
          { required: true, message: "请输入商户昵称", trigger: "blur" },
          { max: 8, message: "商户昵称不超过8个字", trigger: "blur" }
        ],
        manageType: [
          { required: true, message: "请选择经营方式", trigger: "blur" }
        ],
        businessType: [
          { required: true, message: "请选择商户类型", trigger: "change" }
        ],
        discount: [
          { required: true, message: "请输入商户折扣比例", trigger: "blur" }
        ],
        linkName: [
          { required: true, message: "请填写联系人", trigger: "blur" }
        ],
        linkPhone: [
          { required: true, message: "请填写联系电话", trigger: "blur" },
          {
            pattern: /^400[0-9]{7}|^1[345789]\d{9}$|^0[0-9]{2,3}[0-9]{8}/,
            message: "电话格式错误",
            trigger: "blur"
          }
        ],
        sex: [
          { required: true, message: "请选择联系人性别", trigger: "change" }
        ],
        serverClassifyIds: [
          { required: true, message: "请选则服务分类", trigger: "change" }
        ],
        lnglat: [{ required: true, message: "请输入经纬度", trigger: "blur" }]
      },
      roleRules2: {
        // autoCompleteHours: [
        // 	{ pattern: /^([1-9]\d+|[2-9])$/, message: "只能是2到240之间", trigger: "blur" }
        // ],
        exceedOrderNum: [
          { required: true, message: "请填写超单数量", trigger: "blur" }
        ]
      },
      // 可选的一些规则
      optionalRules: {
        parentBusinessId: [
          { required: true, message: "请选择平台商户", trigger: "change" }
        ],
        commission: [
          { required: true, message: "请输入总部管理费占比", trigger: "blur" }
        ],
        settleDay: [
          { required: true, message: "请输入结算日", trigger: "blur" }
        ]
      }
      // hospitalList:[],
    };
  },
  components: {
    Address,
    UploadImg,
    CommonServerSelect,
    UploadOssFile,
    ImageSelect,
    ServerClassifyImgs
  },
  watch: {
    "dataForm.businessType": {
      handler(val) {
        const { roleRules, optionalRules } = this;
        const { parentBusinessId, commission } = optionalRules;
        if (val == 3) {
          this.$delete(roleRules, "parentBusinessId");
          this.$set(roleRules, "commission", commission);
        } else {
          this.$delete(roleRules, "commission");
          this.$set(roleRules, "parentBusinessId", parentBusinessId);
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate();
        });
      },
      immediate: true
    },
    "dataForm.businessVillages": {
      handler(val) {
        console.log("ne", val);
      }
    },
    "dataForm.serverClassifyIds": {
      handler(val) {
        this.dataForm.banners.forEach(item => {
          if (!val.includes(item.serverClassifyId)) {
            item.serverClassifyId = "";
          }
        });
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.userRole = getStorage(USER_INFO).userRole;
      this.detailRole = getStorage(USER_INFO).detailRole;
      this.getRoleInfoList();
      // this.getTreeTwoServerList()
      this.getServerLevel2List();
      // this.getHospitalList()
      // this.getBankList()
      this.getBusinessList();
      if (this.$route.query.id) {
        this.dataForm.businessId = this.$route.query.id;
        this.getCheckoutInfo(this.dataForm.businessId)
        this.getData();
      }
    },
    getData() {
      BusinessApi.getBusinessInfo({
        id: this.dataForm.businessId
      }).then(res => {
        // 编辑开始的时候需要把表格里面的服务分类列表获取到
        // this.handleServer(res.data.serverClassifyIds)

        let info = res.data;

        // // 商户货品库
        // if (!info.servers || info.servers.length == 0) {
        // 	delete info.servers;
        // } else {
        // 	// 获取表格里面所有的三级服务分类数据格式化为数组
        // 	info.servers.forEach(item => {
        // 		item.threeLevelClassList = []
        // 		if (item.thirdClassifyId) {
        // 			item.threeLevelClassList = [{ id: item.thirdClassifyId, name: item.thirdClassifyName }]
        // 		}
        // 	})
        // }
        // 商户经营范围
        if (!info.businessVillages || info.businessVillages.length == 0) {
          // 为了不被后端传来的空值覆盖
          delete info.businessVillages;
        } else {
          // 补全未设置值的经营范围
          let allTypes = [1, 2, 3, 4];
          info.businessVillages.forEach(bv => {
            const index = allTypes.indexOf(bv.type);
            index != -1 && allTypes.splice(index, 1);
          });
          if (allTypes.length > 0) {
            allTypes.forEach(type => {
              let bvAdd = { type: type, villages: [] };
              if (type == 1) {
                bvAdd.villages.push({
                  type: type,
                  startPrice: "",
                  beeperIds: "",
                  levels: 6
                });
              } else if (type == 2) {
                bvAdd.villages.push({
                  type: type,
                  startPrice: "",
                  provinceId: "",
                  provinceName: "",
                  cityId: "",
                  cityName: "",
                  areaId: "",
                  areaName: "",
                  streetId: "",
                  streetName: "",
                  villageId: "",
                  villageName: "",
                  levels: 5,
                  streetIds: [],
                  villageList: []
                });
              } else if (type == 3) {
                bvAdd.villages.push({
                  type: type,
                  startPrice: "",
                  kilometers: "",
                  levels: 7,
                  longitude: "",
                  latitude: "",
                  openFlag: 0
                });
              } else if (type == 4) {
                bvAdd.villages.push({
                  type: type,
                  startPrice: "",
                  provinceId: "",
                  provinceName: "",
                  cityId: "",
                  cityName: "",
                  areaId: "",
                  areaName: "",
                  levels: 3,
                  openFlag: 0
                });
              }
              info.businessVillages.push(bvAdd);
            });
          }
        }

        const banners = [];
        // 修改banner数据格式
        info.banners.forEach(item => {
          const index = banners.findIndex(
            item2 => item2.serverClassifyId == item.serverClassifyId
          );
          if (index != -1) {
            banners[index].list.push(item);
          } else {
            banners.push({
              id: nanoid(),
              serverClassifyId: item.serverClassifyId,
              list: [item]
            });
          }
        });
        info.banners = banners;
        this.$Utils.bindingBean(this.dataForm, info);
        if (this.dataForm.longitude && this.dataForm.latitude) {
          this.dataForm.lnglat =
            this.dataForm.longitude + "," + this.dataForm.latitude;
        }

        // 根据type正序排序，为了实现根据type-1作为数组下标
        this.dataForm.businessVillages.sort((a, b) => {
          return a.type - b.type;
        });

        // 获取到推广员id
        info.promoterId
          ? (this.dataForm.promoterId = Number(info.promoterId))
          : "";

        // 这里必须要使用nextTick函数否则Region组件不会渲染出来，且下面必须使用$set。
        this.$nextTick(() => {
          if (this.dataForm.businessVillages.length > 0) {
            this.dataForm.businessVillages.forEach((item, index) => {
              if (item.type == 2 || item.type == 4) {
                item.villages.forEach((vill, index) => {
                  this.$set(vill, "streetIds", [
                    vill.provinceId,
                    vill.provinceName,
                    vill.cityId,
                    vill.cityName,
                    vill.areaId,
                    vill.areaName,
                    vill.streetId,
                    vill.streetName
                  ]);
                  // 判断是否有小区
                  if (vill.villageId) {
                    this.$set(vill, "villageList", [
                      { id: vill.villageId, name: vill.villageName }
                    ]);
                  }
                });
              }
            });
          }
        });

        this.dataForm.streetIds = [
          this.dataForm.provinceId,
          this.dataForm.provinceName,
          this.dataForm.cityId,
          this.dataForm.cityName,
          this.dataForm.areaId,
          this.dataForm.areaName,
          this.dataForm.streetId,
          this.dataForm.streetName
        ];

        if (info.hours) {
          this.dataForm.hours = info.hours.map(item =>
            Object.assign(item, { list: [item.beginHours, item.endHours] })
          );
        }

        console.log(this.dataForm);
      });
    },
    getCheckoutInfo(businessId) {
      SpecApi.getCheckoutInfo({ businessId }).then(res => {
        if (res.status == 0) {
          this.verifyDiscount = res.data.discount
        }
      })
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getKey() {
      return nanoid();
    },
    // async getHospitalList(){
    // 	const res = await HospitalApi.getHospitalNameList()
    // 	this.hospitalList = res.data||[]
    // },
    getServerClassifyList(id) {
      let {
        serverLevel2List,
        dataForm: { banners, serverClassifyIds }
      } = this;
      serverLevel2List = serverLevel2List.filter(item =>
        serverClassifyIds.includes(item.id)
      );
      return serverLevel2List.filter(
        item =>
          !banners.some(item2 => item2.serverClassifyId == item.id) ||
          item.id == id
      );
    },
    getImgVideo(val) {
      const {
        list,
        mark: { id }
      } = val;
      const target = this.dataForm.banners.find(item => item.id == id);
      target.list = list;
    },
    handlesCImgsDialog(row, index) {
      const { sCImgs } = this;
      if (!row.serverClassifyId) return;
      sCImgs.serverClassifyId = row.serverClassifyId;
      sCImgs.show = true;
      sCImgs.index = index;
    },
    getUrlList(val) {
      const {
        dataForm: { banners },
        sCImgs
      } = this;
      const list = banners[sCImgs.index].list;
      val = val.map((item, index) => ({
        showFlag: false,
        sort: list.length + index + 1,
        type: item.type,
        url: item.url,
        serverClassifyId: sCImgs.serverClassifyId
      }));
      banners[sCImgs.index].list = list.concat(val);
      sCImgs.show = false;
    },
    handleNextOperate(val) {
      this.module = val;
    },
    formatVillageType(cellValue) {
      if (cellValue === 1) {
        return "专属";
      } else if (cellValue === 2) {
        return "小区";
      } else if (cellValue === 3) {
        return "公里数";
      } else if (cellValue === 4) {
        return "省市区";
      }
    },
    getBusinessList() {
      BusinessApi.listIdNameVo({ businessType: 3 }).then(res => {
        this.businessList = res.data;
      });
    },
    // 获取推广员与维护员列表，两个取同一个列表
    getRoleInfoList() {
      LoginApi.roleInfoList().then(res => {
        this.roleList = res.data;
      });
    },
    // 获取服务分类二级列表
    getServerLevel2List() {
      let param = { level: -2 }
      ServerClassifyApi.listServerClassifyTree(param).then(res => {
        this.serverLevel2List = res.data
      })
    },
    // 获取tree形一二级服务列表
    // getTreeTwoServerList() {
    // 	ServerClassifyApi.listServerClassify({ level: -2 }).then(res => {
    // 		this.treeTwoServerList = res.data
    // 	})
    // },
    // 表格中的服务分类改变的时候
    // handleServerClassifyChange(row) {
    // 	row.thirdClassifyId = ""
    // 	row.threeLevelClassList = []
    // },
    // 三级服务列表聚焦,获取三级服务列表
    // handleServerClassify3Focus(row) {
    // 	if (row.serverClassifyId) {
    // 		ServerClassifyApi.listIdName({ level: 3, parentId: row.serverClassifyId }).then(res => {
    // 			row.threeLevelClassList = res.data.map(item => ({ id: item.id, name: item.name }))
    // 		})
    // 	}
    // },
    // 服务分类改变的时候
    // handleServer(val) {
    // 	this.selectedServerList = []
    // 	//从serverLevel2List里面返回新的符合val的数组
    // 	this.serverLevel2List.forEach(item => {
    // 		for (let i = 0; i < val.length; i++) {
    // 			if (item.id == val[i])
    // 				this.selectedServerList.push(item)
    // 		}
    // 	})
    // 	// 当改变上面服务分类servers的时候，判断selectedServerList里面哪些服务分类classifyId存在，不存在就清空
    // 	this.dataForm.servers.forEach(item => {
    // 		let flag = this.selectedServerList.some(item2 => item.serverClassifyId == item2.id)
    // 		if (!flag) {
    // 			item.serverClassifyId = ""
    // 			item.thirdClassifyId = ""
    // 			item.threeLevelClassList = []
    // 		}
    // 	})
    // },
    // 处理自动接单和自动打印
    handlePrintAccept(prop) {
      const { dataForm } = this;
      BusinessApi.checkoutPrinter({
        businessId: this.dataForm.businessId
      }).then(res => {
        if (res.data) {
          if (prop == "autoAccept" && dataForm.autoAccept) {
            dataForm.autoPrint = 1;
            dataForm.autoAcceptPrint = 1;
          }
        } else {
          if (prop == "autoAccept" && dataForm.autoAccept) {
            dataForm.autoAccept = 0;
            this.$message.error("该商户没有配置打印机");
          } else if (prop == "autoPrint" && dataForm.autoPrint) {
            dataForm.autoPrint = 0;
            this.$message.error("该商户没有配置打印机");
          } else if ((prop = "autoAcceptPrint" && dataForm.autoAcceptPrint)) {
            dataForm.autoAcceptPrint = 0;
            this.$message.error("该商户没有配置打印机");
          }
        }
      });
    },
    // 商户折扣比例、起步价、公共服务员配送比例
    handleInput(prop) {
      const { dataForm } = this;
      switch (prop) {
        case "discount":
          dataForm[prop] = parseFloat(parseFloat(dataForm[prop]).toFixed(2));
          if (dataForm.discount < 0 || dataForm.discount > (100 - Number(this.verifyDiscount))) {
            dataForm.discount = 0;
            this.$message.error(`商户折扣比例只能是0-${(100 - Number(this.verifyDiscount))}之间`);
          }
          break;
        case "packageDiscount":
          dataForm[prop] = parseFloat(parseFloat(dataForm[prop]).toFixed(2));
          if (dataForm.packageDiscount < 0 || dataForm.packageDiscount > (100 - Number(this.verifyDiscount))) {
            dataForm.packageDiscount = 0;
            this.$message.error(`打包费折扣比例只能是0-${(100 - Number(this.verifyDiscount))}之间`);
          }
          break;
        // case 'startPrice':
        // 	dataForm[prop] = parseFloat(parseFloat(dataForm[prop]).toFixed(2))
        // 	if (dataForm.startPrice < 0) {
        // 		dataForm.startPrice = 0
        // 	}
        // 	break
        case "percentage":
          dataForm[prop] = parseFloat(parseFloat(dataForm[prop]).toFixed(2));
          if (dataForm.percentage < 0 || dataForm.percentage > 100) {
            dataForm.percentage = 0;
          }
          break;
        case "cashDay":
          dataForm.cashInfo.cashDay = dataForm.cashInfo.cashDay.replace(
            /([^\d]*)|(^0$)/g,
            ""
          );
          break;
        case "autoCompleteHours":
          const reg = /(^[1-9][0-9]?$)|(^[1-2][0-3][0-9]$)|^240$/;
          if (!reg.test(dataForm.autoCompleteHours)) {
            dataForm.autoCompleteHours = "";
          }

          break;
        // case ''
      }
    },
    // 上面输入框商户折扣比例改变
    // handleDiscountChange() {
    // 	this.dataForm.servers.forEach(item => {
    // 		item.discount = this.dataForm.discount
    // 	})
    // },
    // 列表价格、配送费、包装费的输入限制
    handleMoneyInputList(row, flag) {
      // flag为0表示原价，为1表示配送费，为2表示包装费,3表示商户折扣比例
      if (!flag) {
        // 只保留两位小数
        row.price = parseFloat(parseFloat(row.price).toFixed(2));
        !row.price ? (row.price = 0) : "";
      } else if (flag == 1) {
        row.deliveryFee = parseFloat(parseFloat(row.deliveryFee).toFixed(2));
        !row.deliveryFee ? (row.deliveryFee = 0) : "";
      } else if (flag == 2) {
        row.packageFee = parseFloat(parseFloat(row.packageFee).toFixed(2));
        !row.packageFee ? (row.packageFee = 0) : "";
      } else if (flag == 3) {
        row.discount = parseFloat(parseFloat(row.discount).toFixed(2));
        if (row.discount && row.discount > 99.72) {
          row.discount = 0;
          this.$message.error("商户折扣比例只能是0-99.72之间");
        } else if (row.discount) {
          row.discount = parseFloat(parseFloat(row.discount).toFixed(2));
        } else {
          row.discount = 0;
        }
      }
    },
    // 列表价格或者配送费改变
    handleMoneyChangeList(row) {
      let price = row.price || 0;
      let deliveryFee = row.deliveryFee || 0;
      row.salePrice = parseFloat((price + deliveryFee).toFixed(2));
    },
    addTime() {
      this.dataForm.hours.push({ list: ["", ""] });
    },
    subTime(index) {
      this.dataForm.hours.splice(index, 1);
    },
    // 获取商图片
    getImgUrl(val) {
      if (val.uploadFileList.length > 0) {
        this.$Utils.notifySuccess("上传成功");
        const { dataForm } = this;
        const url = val.uploadFileList[0];
        const { type, index } = val.param;

        switch (type) {
          case 1:
            dataForm.businessLogo = url;
            break;
          case 5:
            dataForm.businessLicense = url;
            break;
        }
      }
    },
    getLngLat(type) {
      if (type == 1) {
        window.open(
          "https://api.map.baidu.com/lbsapi/getpoint/index.html",
          "_blank"
        );
      } else {
        window.open("https://lbs.qq.com/getPoint", "_blank");
      }
    },
    addBtnRegion(type) {
      if (type == 1) {
        this.dataForm.businessVillages[type - 1].villages.push({
          type: type,
          startPrice: "",
          beeperIds: "",
          levels: 6
        });
      } else if (type == 2) {
        this.dataForm.businessVillages[type - 1].villages.push({
          type: type,
          startPrice: "",
          provinceId: "",
          provinceName: "",
          cityId: "",
          cityName: "",
          areaId: "",
          areaName: "",
          streetId: "",
          streetName: "",
          villageId: "",
          villageName: "",
          levels: 5,
          streetIds: [],
          villageList: []
        });
      } else if (type == 3) {
        this.dataForm.businessVillages[type - 1].villages.push({
          type: type,
          startPrice: "",
          kilometers: "",
          levels: 7
        });
      } else if (type == 4) {
        this.dataForm.businessVillages[type - 1].villages.push({
          type: type,
          startPrice: "",
          provinceId: "",
          provinceName: "",
          cityId: "",
          cityName: "",
          areaId: "",
          areaName: "",
          levels: 3
        });
      }
    },
    subBtnRegion(type, index) {
      let temp = this.dataForm.businessVillages[type - 1].villages;
      if (temp[index].businessVillageId) {
        this.$confirm(
          "该操作将直接删除经营区域以及该经营区域下的所有产品，确定删除吗？",
          "提示",
          {}
        ).then(res => {
          BusinessVillageApi.deleteVillageAndGoods({
            businessVillageId: temp[index].businessVillageId
          }).then(() => {
            temp.splice(index, 1);
            this.$Utils.notifySuccess("删除成功");
          });
        });
      } else {
        temp.splice(index, 1);
      }
    },
    handleVillageFocus(type, streetIds, index) {
      // 点击小区的时候调用接口
      const arr = this.dataForm.businessVillages[type - 1].villages;
      let levels = arr[index].levels;
      if (levels == 3 || levels == 4 || levels == 5) {
        streetIds = streetIds.filter(item => typeof item == "number"); //有名字的话就要过滤掉
        let param = {
          provinceId: streetIds[0],
          cityId: streetIds[1],
          areaId: streetIds[2],
          streetId: streetIds[3],
          name: ""
        };
        VillageApi.villageList(param).then(res => {
          let data = res.data;
          if (type == 2) {
            data = data.filter(item => {
              return !arr.some(
                (item2, index2) => item2.villageId == item.id && index2 != index
              );
            });
          }
          this.$set(arr[index], "villageList", data);
          // arr[index].villageList = data
        });
      }
    },
    handleVillageChange(row, index) {
      // 需要拿到小区的名字放在数组里一起传给后台
      let value = this.dataForm.businessVillages[row.type - 1].villages[index];
      if (row.villageId) {
        let obj = value.villageList.find(item => item.id == row.villageId);
        value.villageName = obj.name;
      } else {
        value.villageName = "";
      }
    },
    handleUpdateBusiness() {
      if (this.dataForm.lnglat) {
        let jwd = this.dataForm.lnglat.split(",");
        if (jwd && jwd.length > 1) {
          this.dataForm.longitude = jwd[0];
          this.dataForm.latitude = jwd[1];
        }
      }
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            this.editData();
          });
        }
      });
    },
    // handleUpdateServer(isUpdate) {
    // 	this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
    // 		.then(() => {
    // 			// 对服务信息表进行处理，先去掉空的行，再判断是否哪一行信息没有填写完整
    // 			this.dataForm.servers = this.dataForm.servers.filter(item => {
    // 				return item.serverClassifyId || item.name || item.price || item.price === 0
    // 			})

    // 			let validateRes = this.dataForm.servers.every(item => {
    // 				if (!item.serverClassifyId || !item.thirdClassifyId || !item.name || !item.images || !item.price && item.price !== 0) {
    // 					this.$message.error("请完善表中的服务信息")
    // 					return
    // 				} else {
    // 					return true
    // 				}
    // 			})
    // 			if (!validateRes) return

    // 			// 把需要提交的数据过滤
    // 			let servers = this.dataForm.servers.map(item => {
    // 				return {
    // 					serverId: item.serverId ? item.serverId : null,
    // 					//sort:item.sort?item.sort:999,
    // 					serverClassifyId: item.serverClassifyId,
    // 					thirdClassifyId: item.thirdClassifyId,
    // 					name: item.name,
    // 					images: item.images,
    // 					introduce: item.introduce,
    // 					describes: item.describes,
    // 					visitFlag: item.visitFlag,
    // 					shopFlag: item.shopFlag,
    // 					remoteFlag: item.remoteFlag,
    // 					fastFlag: item.fastFlag,
    // 					deliveryFlag: item.deliveryFlag,
    // 					price: item.price,
    // 					discount: item.discount,
    // 					salePrice: item.salePrice,
    // 					deliveryFee: item.deliveryFee,
    // 					packageFee: item.packageFee,
    // 				}
    // 			})

    // 			let param = {
    // 				businessId: this.dataForm.businessId,
    // 				servers: servers,
    // 				update: 1
    // 			}
    // 			// 是否一键同步修改经营产品
    // 			if (isUpdate) {
    // 				param.update = 1
    // 			}
    // 			BusinessServerApi.updateBusinessServer(param).then(res => {
    // 				this.$Utils.notifySuccess()
    // 			})

    // 		});
    // },
    // 营业设置保存
    async handlePortionInfo() {
      let {
        hours,
        autoAccept,
        autoOpen,
        autoCompleteHours,
        autoPrint,
        autoAcceptPrint,
        percentage,
        packageDiscount,
        voiceFlag,
        printModel,
        openFlag,
        allowMonthSettle,
        allowOpenPhone,
        takeOrdersWay,
        workOffWay,
        exceedOrderNum,
        taskSingleTimeout,
        taskTotalTimeout,
        voiceLevel
      } = this.dataForm;
      this.dataForm.hours = hours = hours.filter(item => item.list[0]);
      hours = hours.map(item => ({
        beginHours: item.list[0],
        endHours: item.list[1]
      }));
      const params = {
        businessId: this.dataForm.businessId,
        hours,
        autoAccept,
        autoOpen,
        autoPrint,
        autoAcceptPrint,
        // startPrice,
        autoCompleteHours,
        percentage,
        packageDiscount,
        voiceFlag,
        printModel,
        openFlag,
        allowMonthSettle,
        allowOpenPhone,
        exceedOrderNum,
        taskSingleTimeout,
        taskTotalTimeout,
        takeOrdersWay,
        workOffWay,
        voiceLevel
      };
      const valid = await this.$refs.dataForm2.validate();
      if (!valid) return;
      this.$confirm(
        message.MSG_CONFIRM_SAVE_ALTER,
        message.TITLE_PROMPT,
        {}
      ).then(() => {
        BusinessApi.setPortionInfo(params).then(res => {
          this.$Utils.notifySuccess("设置成功");
        });
      });
    },
    async handleUpdateScope() {
      await this.$confirm(
        message.MSG_CONFIRM_SAVE_ALTER,
        message.TITLE_PROMPT,
        {}
      );
      const { businessVillages, businessId, detailType } = this.dataForm;

      // 对经营区域表进行处理，先去掉空的行，再判断是否至少加了一行数据(必须加)，最后过滤筛选出需要提交的数据
      if (detailType == 1) {
        businessVillages[0].villages = businessVillages[0].villages.filter(
          item => item.beeperIds
        );
        businessVillages[2].villages = businessVillages[2].villages.filter(
          item => item.kilometers
        );
        businessVillages[3].villages = businessVillages[3].villages.filter(
          item => item.provinceId
        );
      } else {
        businessVillages[0].villages = [];
        businessVillages[2].villages = [];
        businessVillages[3].villages = [];
      }
      businessVillages[1].villages = businessVillages[1].villages.filter(
        item => item.provinceId
      );

      if (businessVillages.filter(item => item.villages).length == 0) {
        this.$message.error(
          detailType == 1 ? "请至少填写一个经营区域" : "请填写范围"
        );
        return;
      }
      if (businessVillages.some(item => item.type === 2)) {
        const _this = this;
        let allValid = true;

        businessVillages.forEach((e, i) => {
          if (!e.villages.every(c => c.villageId !== "")) {
            allValid = false;
            return;
          }
        });

        if (!allValid) {
          _this.$message.error("请选择小区");
          return;
        }
      }
      await BusinessVillageApi.updateBusinessVillage({
        businessId,
        businessVillages
      });
      this.$Utils.notifySuccess();
    },
    // banner图片保存
    async handleBanners() {
      let { businessId, banners } = this.dataForm;
      this.dataForm.banners = banners = banners.filter(
        item => item.serverClassifyId || item.list.length
      );
      for (let item of banners) {
        if (!item.serverClassifyId) {
          this.$message.error("请选择服务分类");
          return;
        }
        if (!item.list.length) {
          this.$message.error("请选择图片");
          return;
        }
      }

      await this.$confirm("确定保存吗?", "提示", {});
      banners.forEach(item =>
        item.list.forEach(
          item2 => (item2.serverClassifyId = item.serverClassifyId)
        )
      );
      const params = {
        businessId,
        list: banners.flatMap(item => item.list)
      };
      await ServerClassifyApi.setBanners(params);
      this.$message.success("设置成功");
    },
    // // 公共货品库
    // handleCommonServer() {
    // 	if (!this.dataForm.serverClassifyIds || this.dataForm.serverClassifyIds.length == 0) {
    // 		this.$message({
    // 			type: "error",
    // 			message: "请先选择基本信息中的服务分类"
    // 		})
    // 		return
    // 	}
    // 	this.$refs.commonServerSelect.handleCreate()
    // },
    // 获取服务列表
    getServerList(val) {
      val.list.forEach(item => {
        this.dataForm.servers.push({
          serverClassifyId: item.serverClassifyId,
          thirdClassifyId: item.thirdClassifyId,
          thirdClassifyName: item.thirdClassifyName,
          threeLevelClassList: [
            { id: item.thirdClassifyId, name: item.thirdClassifyName }
          ], //三级服务分类列表，不需要提交
          name: item.name,
          images: item.images,
          introduce: item.introduce,
          describes: item.describes,
          visitFlag: item.visitFlag, //是否上们，1代表是
          shopFlag: item.shopFlag, //是否到店，1代表是，0代表不是
          remoteFlag: item.remoteFlag, //是否远程，1代表是，0代表不是
          fastFlag: item.fastFlag, //紧急通知
          deliveryFlag: item.deliveryFlag, //是否需配送费
          price: item.price,
          salePrice: item.salePrice,
          deliveryFee: item.deliveryFee,
          packageFee: item.packageFee, //包装费
          discount: item.discount
        });
      });
    },
    async sureClick() {
      const valid = await Promise.all([
        this.$refs.dataForm.validate(),
        this.$refs.dataForm2.validate()
      ]);
      if (!valid) return;
      let { businessVillages, detailType, hours, banners } = this.dataForm;

      // 对服务信息表进行处理，先去掉空的行，再判断是否哪一行信息没有填写完整
      // this.dataForm.servers = servers = servers.filter(item => {
      // 	return item.serverClassifyId || item.name || item.price || item.price === 0
      // })

      // let validateRes = servers.every(item => {
      // 	if (!item.serverClassifyId || !item.thirdClassifyId || !item.name || !item.images || !item.price && item.price !== 0) {
      // 		this.$message.error("请完善表中的服务信息")
      // 		return
      // 	} else {
      // 		return true
      // 	}
      // })
      // if (!validateRes) return

      // 把需要提交的数据过滤
      // this.dataForm.servers = this.dataForm.servers.map(item => {
      // 	return {
      // 		serverId: item.serverId ? item.serverId : null,
      // 		//sort:item.sort?item.sort:999,
      // 		serverClassifyId: item.serverClassifyId,
      // 		thirdClassifyId: item.thirdClassifyId,
      // 		name: item.name,
      // 		images: item.images,
      // 		introduce: item.introduce,
      // 		describes: item.describes,
      // 		visitFlag: item.visitFlag,
      // 		shopFlag: item.shopFlag,
      // 		remoteFlag: item.remoteFlag,
      // 		fastFlag: item.fastFlag,
      // 		deliveryFlag: item.deliveryFlag,
      // 		price: item.price,
      // 		discount: item.discount,
      // 		salePrice: item.salePrice,
      // 		deliveryFee: item.deliveryFee,
      // 		packageFee: item.packageFee,
      // 	}
      // })
      // 对经营区域表进行处理，先去掉空的行，再判断是否至少加了一行数据(必须加)，最后过滤筛选出需要提交的数据
      if (detailType == 1) {
        businessVillages[0].villages = businessVillages[0].villages.filter(
          item => item.beeperIds
        );
        businessVillages[2].villages = businessVillages[2].villages.filter(
          item => item.kilometers
        );
        businessVillages[3].villages = businessVillages[3].villages.filter(
          item => item.provinceId
        );
      } else {
        businessVillages[0].villages = [];
        businessVillages[2].villages = [];
        businessVillages[3].villages = [];
      }

      // businessVillages[0].villages = businessVillages[0].villages.filter(item => item.beeperIds)
      businessVillages[1].villages = businessVillages[1].villages.filter(
        item => item.villageId
      );
      // businessVillages[2].villages = businessVillages[2].villages.filter(item => item.kilometers)
      // businessVillages[3].villages = businessVillages[3].villages.filter(item => item.provinceId)
      if (businessVillages.filter(item => item.villages).length == 0) {
        this.$message.error(
          detailType == 1 ? "请至少填写一个经营区域" : "请填写范围"
        );
        return;
      }
      // this.businessVillages = businessVillages
      if (this.dataForm.lnglat) {
        let jwd = this.dataForm.lnglat.split(",");
        if (jwd && jwd.length > 1) {
          this.dataForm.longitude = jwd[0];
          this.dataForm.latitude = jwd[1];
        }
      }

      // let { hours } = this.dataForm
      this.dataForm.hours = hours = hours.filter(item => item.list[0]);
      this.hours = hours.map(item => {
        const obj = { ...item };
        obj.beginHours = obj.list[0];
        obj.endHours = obj.list[1];
        delete obj.list;
        return obj;
      });

      banners.forEach(item =>
        item.list.forEach(
          item2 => (item2.serverClassifyId = item.serverClassifyId)
        )
      );
      this.banners = banners.flatMap(item => item.list);
      // 账户校验
      // if(!this.validateBankCard()) return
      await this.$confirm(
        message.MSG_CONFIRM_SAVE_ALTER,
        message.TITLE_PROMPT,
        {}
      );
      this.addData();
    },
    addData() {
      let param = {
        businessName: this.dataForm.businessName,
        businessShortName: this.dataForm.businessShortName,
        businessMiniName: this.dataForm.businessMiniName,
        introduce: this.dataForm.introduce,
        businessLogo: this.dataForm.businessLogo,
        businessLicense: this.dataForm.businessLicense,
        manageType: this.dataForm.manageType,
        serverClassifyIds: this.dataForm.serverClassifyIds,
        businessType: this.dataForm.businessType,
        voiceFlag: this.dataForm.voiceFlag,
        printModel: this.dataForm.printModel,
        voiceLevel: this.dataForm.voiceLevel,
        openFlag: this.dataForm.openFlag,
        allowMonthSettle: this.dataForm.allowMonthSettle,
        allowOpenPhone: this.dataForm.allowOpenPhone,
        takeOrdersWay: this.dataForm.takeOrdersWay,
        workOffWay: this.dataForm.workOffWay,
        exceedOrderNum: this.dataForm.exceedOrderNum,
        taskSingleTimeout: this.dataForm.taskSingleTimeout,
        taskTotalTimeout: this.dataForm.taskTotalTimeout,
        discount: this.dataForm.discount,
        packageDiscount: this.dataForm.packageDiscount,
        linkName: this.dataForm.linkName,
        // hospitalId:this.dataForm.hospitalId,
        sex: this.dataForm.sex,
        linkPhone: this.dataForm.linkPhone,
        linkPhoneTwo: this.dataForm.linkPhoneTwo,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        address: this.dataForm.address,
        latitude: this.dataForm.latitude,
        longitude: this.dataForm.longitude,
        remark: this.dataForm.remark,
        // businessBeginHours: this.dataForm.businessHours ? this.dataForm.businessHours[0] : "",
        // businessEndHours: this.dataForm.businessHours ? this.dataForm.businessHours[1] : "",
        promoterId: this.dataForm.promoterId,
        keeperId: this.dataForm.keeperId,
        servers: this.dataForm.servers,
        businessVillages: this.dataForm.businessVillages,
        hours: this.hours,
        autoOpen: this.dataForm.autoOpen,
        autoPrint: this.dataForm.autoPrint,
        autoAcceptPrint: this.dataForm.autoAcceptPrint,
        autoAccept: this.dataForm.autoAccept,
        autoCompleteHours: this.dataForm.autoCompleteHours,
        // startPrice: this.dataForm.startPrice,
        percentage: this.dataForm.percentage,
        banners: this.banners,
        detailType: this.dataForm.detailType
      };
      if (param.businessType == 3) {
        param.commission = this.dataForm.commission;
      } else {
        param.commission = 0;
        param.parentBusinessId = this.dataForm.parentBusinessId;
      }
      BusinessApi.addBusiness(param).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData() {
      let param = {
        businessId: this.dataForm.businessId,
        serverClassifyIds: this.dataForm.serverClassifyIds,
        businessType: this.dataForm.businessType,
        businessName: this.dataForm.businessName,
        businessShortName: this.dataForm.businessShortName,
        businessMiniName: this.dataForm.businessMiniName,
        introduce: this.dataForm.introduce,
        businessLogo: this.dataForm.businessLogo,
        businessLicense: this.dataForm.businessLicense,
        manageType: this.dataForm.manageType,
        discount: this.dataForm.discount,
        linkName: this.dataForm.linkName,
        // hospitalId:this.dataForm.hospitalId,
        sex: this.dataForm.sex,
        linkPhone: this.dataForm.linkPhone,
        linkPhoneTwo: this.dataForm.linkPhoneTwo,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        address: this.dataForm.address,
        latitude: this.dataForm.latitude,
        longitude: this.dataForm.longitude,
        remark: this.dataForm.remark,
        businessState: this.dataForm.businessState,
        // businessBeginHours: this.dataForm.businessHours ? this.dataForm.businessHours[0] : "",
        // businessEndHours: this.dataForm.businessHours ? this.dataForm.businessHours[1] : "",
        promoterId: this.dataForm.promoterId,
        keeperId: this.dataForm.keeperId,
        detailType: this.dataForm.detailType
      };
      if (param.businessType == 3) {
        param.commission = this.dataForm.commission;
      } else {
        param.commission = 0;
        param.parentBusinessId = this.dataForm.parentBusinessId;
      }
      BusinessApi.editBusiness(param).then(data => {
        this.$Utils.notifySuccess();
        //this.returnList();
      });
    },
    handleItemChange(val) {
      const { index, mark } = val;
      if (index === 0 || index) {
        // 当是列表里面的数据的时候，传了索引过去，所以接收索引
        let region = this.dataForm.businessVillages[mark.type - 1].villages[
          index
        ];
        /*if (val.levels == 1 || val.levels == 2) {
          // 只选到第一级和第二级别那么就直接清空
          region.villageList = [] //清空小区列表
          region.villageId = "" //清空对应的小区id
          region.villageName = ""
          this.$refs.region.clearStreetIds()
          this.$message.error("请至少选至三级地区")
        }*/

        if (mark.type == 2) {
          // 小区
          // 没办法取到具体的哪个region，所以判断无效。this.$refs.region.clearStreetIds()报错，因为this.$refs.region取的是多个
          /*if (val.levels != 4) {
            region.villageList = [] //清空小区列表
            region.villageId = "" //清空对应的小区id
            region.villageName = ""
            this.$refs.region.clearStreetIds()
            this.$message.error("请选至街道")
            return
          }*/
          region.villageList = []; //清空小区列表
          region.villageId = ""; //清空对应的小区id
          region.villageName = ""; //清空小区对应的名字
          region.levels = "";
          region.provinceId = val.provinceId;
          region.provinceName = val.provinceName;
          region.cityId = val.cityId;
          region.cityName = val.cityName;
          region.areaId = val.areaId;
          region.areaName = val.areaName;
          region.streetId = val.streetId;
          region.streetName = val.streetName;
          region.levels = 5;
        } else if (mark.type == 4) {
          // 省市区
          region.provinceId = val.provinceId;
          region.provinceName = val.provinceName;
          region.cityId = val.cityId;
          region.cityName = val.cityName;
          region.areaId = val.areaId;
          region.areaName = val.areaName;
          region.levels = val.levels;
        }

        if (val.provinceId) {
          region.streetIds = [
            val.provinceId,
            val.cityId,
            val.areaId,
            val.streetId
          ];
        } else {
          region.streetIds = [];
        }
      } else {
        // 没有传索引过去
        this.dataForm.provinceId = val.provinceId;
        this.dataForm.provinceName = val.provinceName;
        this.dataForm.cityId = val.cityId;
        this.dataForm.cityName = val.cityName;
        this.dataForm.areaId = val.areaId;
        this.dataForm.areaName = val.areaName;
        this.dataForm.streetId = val.streetId;
        this.dataForm.streetName = val.streetName;
        this.dataForm.streetIds = [
          val.provinceId,
          val.cityId,
          val.areaId,
          val.streetId
        ];
      }
    },
    getLngLat(type) {
      if (type == 1) {
        window.open(
          "https://api.map.baidu.com/lbsapi/getpoint/index.html",
          "_blank"
        );
      } else {
        window.open("https://lbs.qq.com/getPoint", "_blank");
      }
    },
    updateBusinessGoodsVillage() {
      this.$router.push({
        path: "/business/businessVillageGoodsAdd",
        query: { id: this.dataForm.businessId }
      });
    },
    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.back();
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";
</style>
<style lang="scss" scoped>
@import "@/assets/css/views/addType.scss";
</style>
<style lang="scss" scoped>
.bussiness-villgae-header {
  padding: 4px 0;
  font-size: 14px;
  color: #1e6abc;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-img {
  &::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
}

.flex {

  // width: 300px;
  .flex-input {
    // width:240px;
    margin: 0 10px !important;

    &::v-deep .el-input__inner {
      width: 100% !important;
    }
  }
}

.fourth-title {
  padding-bottom: 7px;
  font-size: 15px;
  color: #409eff;
}

::v-deep .el-cascader__search-input {
  background-color: #f7f7f7 !important;
}
</style>
